import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout'
import Login from '@/views/Login'
import NotFound from '@/views/404'
import Search from '@/views/Search'
import SearchResult from '@/views/Search/searchResult'
import Article from '@/views/Article'
import Edit from '@/views/Layout/User/edit'

// 引入二级路由
import Home from '@/views/Layout/Home'
import Qa from '@/views/Layout/Qa'
import Video from '@/views/Layout/Video'
import User from '@/views/Layout/User'

// 引入仓库
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      { path: '/qa', component: Qa },
      { path: '/video', component: Video },
      { path: '/user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/article/:id', component: Article },
  { path: '/search', component: Search },
  { path: '/search/result', component: SearchResult },
  { path: '/user/edit', component: Edit },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})
const loginUrl = ['/user', '/user/edit']
// 导航守卫拦截未登录用户
router.beforeEach((to, from, next) => {
  // 判断是否有token
  const token = store.state.user.token.token
  // 有token就直接放行
  if (token) {
    next()
  } else {
    // 没有token 判断去往哪里  如果是我的页面则进行拦截 去登陆页面
    if (loginUrl.some(v => v === to.path)) {
      // router.push('/login')
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
